package com.ncucoder.soms.config;

import com.google.common.collect.Lists;
import com.ncucoder.soms.util.JwtTokenUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

/**
 * @author <a href="https://www.ncucoder.com">hsowan</a>
 * @date 2019-07-12
 **/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    private ApiInfo apiInfo() {
        return new ApiInfo("SOMS",
                "Supermarket Orders Management System 超市订单管理系统",
                "V1.0.0", "",
                new Contact("hsowan", "https://www.ncucoder.com", "hsowan.me@gmail.com"),
                "MIT",
                "https://github.com/hsowan/SOMS/blob/master/LICENSE",
                new ArrayList<>());
    }

    private ApiKey apiKey() {
        // 这里第一个参数name需要和defaultAuth里返回的参数reference一样, 即JWT
        return new ApiKey("JWT", "Authorization", "header");
    }

    @Bean
    public Docket swaggerDocker() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("NCUCoder")
                .forCodeGeneration(true)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.ncucoder.soms.controller"))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(Lists.newArrayList(apiKey()))
                .securityContexts(Lists.newArrayList(securityContext()))
                .apiInfo(apiInfo());
    }

    @Bean
    public SecurityContext securityContext() {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.any())
                .build();
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope
                = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Lists.newArrayList(
                new SecurityReference("JWT", authorizationScopes));
    }

}
